import Component, {forceLogin, middleware, get, post} from '../ZES'
import multer from 'koa-multer';
import {uploadFile} from "../QiniuUtils";
import fs from 'fs';
import crypto from 'crypto';
import Path from 'path';
import fetch from 'node-fetch';

function fileMd5(path) {
    return new Promise((resolve,reject)=> {
        let md5sum = crypto.createHash('md5');
        let stream = fs.createReadStream(path);
        stream.on('data', function (chunk) {
            md5sum.update(chunk);
        });
        stream.on('end', function () {
            let str = md5sum.digest('hex').toUpperCase();
            //console.log('文件:' + path + ',MD5签名为:' + str + '.耗时:' + (new Date().getTime() - start) / 1000.00 + "秒");
            resolve(str);
        });
        stream.on('error',function(err){
            reject(err);
        })
    });
}

const upload = multer({ dest: 'build/runtime/upload' });
export default class File extends Component{

    @post
    @middleware(forceLogin,upload.single('file'))
    async upload(cx) {
        let f = cx.req.file;
        if (f==null) return cx.fail("文件为空");
        let md5=await fileMd5(f.path);
        let userPath="RPGCreatorFile/"+md5+Path.extname(f.originalname);
        let guessPath="http://7xsskj.com2.z0.glb.clouddn.com/"+userPath;
        //console.log(guessPath);
        let body=await fetch(guessPath,{"method":"HEAD"});
        //console.log(body.status);
        if (body.status==200){
            fs.unlink(f.path,()=>{});
            return {
                message:"文件已经存在，不需要再次上传",
                code:"exist",
                url:guessPath
            }
        }else{
            let data = await uploadFile(f.path, userPath);
            let url="http://7xsskj.com2.z0.glb.clouddn.com/" + data.key;
            //console.log(url);
            fs.unlink(f.path,()=>{});
            return {
                message:"上传成功",
                code:"success",
                url:url
            }
        }
    }

    @get query(req){
        let id=req.query.id;
        if (id==null) return null;
        return this.db.queryOne('file',{id});
    }
}
